package com.fbli.jedis;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Transaction;

import java.util.List;

public class SecKill_redis {
    public static void main(String[] args) {
        doSecKill("1","0101");
    }
    public static boolean doSecKill(String uid,String prodid){
        //1.uid和prodid非空判断
        if(uid==null || prodid==null){
            return false;
        }
        //2.连接redis
        //Jedis jedis = new Jedis("192.168.174.128",6379);
        //通过连接池连接
        JedisPool jedisPoolInstance = JedisPoolUtil.getJedisPoolInstance();
        Jedis jedis = jedisPoolInstance.getResource();
        //3.拼接key
        //库存key
        String kcKey="sk:"+prodid+":qt";
        //3.2秒杀成功用户key
        String userKey="sk:"+prodid+":user";
        //监视库存
        jedis.watch(kcKey);
        //4.获取库存，如果库存为空，秒杀还没开始
        String kc = jedis.get(kcKey);
        if(kc==null){
            System.out.println("秒杀还没开始，请等待");
            jedis.close();
            return false;
        }
        //5.判断用户是否重复秒杀操作
        if(jedis.sismember(userKey,uid)){
            System.out.println("已经秒杀成功了,不能重复秒杀");
            jedis.close();
            return false;
        }
        //6.判断如果商品数量，库存数小于1，秒杀结束
        int i = Integer.parseInt(kc);
        if (i<=0){
            System.out.println("秒杀已经结束");
            jedis.close();
            return false;
        }
        //7.秒杀过程
        //使用事务
        Transaction multi = jedis.multi();
        //组队操作
        multi.decr(kcKey);
        multi.sadd(userKey,uid);
        //执行
        List<Object> result = multi.exec();
        if (result==null || result.size()==0){
            jedis.close();
            return false;
        }

        //7.1 库存-1
        //jedis.decr(kcKey);
        //7.2把秒杀成功用户添加到清单里面
        //jedis.sadd(userKey,uid);
        System.out.println("秒杀成功了");
        jedis.close();
        return true;
    }
}
